﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using GmPrizedrawTool;
using Liuliu.ScriptEngine;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;

internal class Program
{
    public static DmPlugin dm = new Liuliu.ScriptEngine.DmPlugin();
    public static Process golobalProcess;//当前进程
    public static string ApiAddress;// 接口地址
    public static string GmToolDomain;//GM工具地址
    public static string UserName;//GM账号
    public static string UserPwd;//GM账号密码
    public static string ProcessAddress = $"E:\\FSCQDEBUG\\";
    public static ServerModel serverModel;//当前服务区
    public static string RewardInterval;//抽奖奖励时间间隔
    public static string RandromInterval;//随机Boss刷新间隔
    public static int NoticePointLevel;//财神抽奖坐标报告等级限制

    public static void Main(string[] args)
    {
        Console.WriteLine("软件启动!");
        // 读取配置信息
        var builder = new ConfigurationBuilder()
            .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
        IConfigurationRoot configuration = builder.Build();

        // 读取配置信息
        ApiAddress = configuration["ApiDomain"];
        GmToolDomain = configuration["GmToolDomain"];
        UserName = configuration["UserName"];
        UserPwd = configuration["UserPwd"];
        ProcessAddress = configuration["ProcessAddress"];
        NoticePointLevel = Convert.ToInt32(configuration["NoticePointLevel"]);

        ///通过接口获取服务区列表
        serverModel = GetServerInfo(ApiAddress);

        //根据选择的区、清理掉online_table表数据
        //CommonFun.HttpGet($"{ApiAddress}Api/Interface/ClearServerOnlineTable?serverid={serverModel.Id}");

        Console.WriteLine("===请选择要执行的操作：==========================");
        Console.WriteLine("1、监控BOSS死亡");
        Console.WriteLine("2、系统抽奖");
        //Console.WriteLine("3、批量移动玩家位置");
        int actionType = Convert.ToInt32(Console.ReadLine());
        int userNum = 0;
        string movePoint = "";
        if (actionType == 3)
        {
            Console.WriteLine("===请输入要移动玩家的数量：");
            userNum = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("===请输入要移动的坐标X,Y：");
            movePoint = Console.ReadLine().ToString();
            if (string.IsNullOrEmpty(movePoint)) {
                Console.WriteLine("未输入移动坐标，请重启程序"); 
                Thread.Sleep(20000);
                return;
            }
        }
        else if (actionType == 2) {
            RewardInterval = configuration["RewardInterval"];
            RandromInterval = configuration["RandromInterval"];
        }

        //启动软件，执行登录
        string zfsconnect = $"zfs4connect;name={serverModel.ServerName};ip={serverModel.IP};port={serverModel.Port};LogServerIP={serverModel.IP};LogServerPort={serverModel.Port}";
        //string zfsconnect = "zfs4connect;name=远古;ip=192.168.1.11;port=21820;LogServerIP=192.168.1.11;LogServerPort=21820";
        ProcessStartInfo ps = new ProcessStartInfo();
        ps.FileName = $"{ProcessAddress}gc.exe";
        ps.WorkingDirectory = ProcessAddress;
        ps.Arguments = zfsconnect;
        ps.UseShellExecute = true;
        try
        {
            using (golobalProcess = Process.Start(ps))
            {
                golobalProcess.Exited += Process_Exited;
                int Hwnd = (int)golobalProcess.MainWindowHandle;
                int Seconed = 0;
                while (Hwnd <= 0)
                {
                    if (Seconed >= 30000)
                    {
                        Console.WriteLine("游戏启动异常");
                        return;//超过30s视为未启动成功
                    }
                    Hwnd = (int)golobalProcess.MainWindowHandle;
                    Seconed += 100;
                    Thread.Sleep(100);//等待软件启动完成
                }
                //dm.SetWindowText(Hwnd, $"{Hwnd}");
                LoginGame.StartLogin(Hwnd, actionType, userNum, movePoint);
            }
            
            Console.WriteLine("客户端启动成功");
        }
        catch (Exception ex)
        {
            // 处理异常
            Console.WriteLine($"客户端启动出险异常: {ex.Message}");
        }


        Console.ReadLine();
    }

    private static void Process_Exited(object? sender, EventArgs e)
    {
        Console.WriteLine(
            $"Exit time    : {golobalProcess.ExitTime}\n" +
            $"Exit code    : {golobalProcess.ExitCode}\n");
    }

    /// <summary>
    /// 获取要登录的服务器信息
    /// </summary>
    /// <param name="ApiAddress"></param>
    /// <returns></returns>
    private static ServerModel GetServerInfo(string? ApiAddress)
    {
        string serverAddress = $"{ApiAddress}Api/Interface/GetClientInfo";
        string serverInfoStr = CommonFun.HttpGet(serverAddress);
        serverInfoStr = CommonFun.DeAes(serverInfoStr.Substring(1).TrimEnd('\"'));
        serverInfoStr = serverInfoStr.Substring(serverInfoStr.IndexOf('{')).TrimEnd('"').Replace("\\", "");
        ReturnMsgModel returnMsg = JsonConvert.DeserializeObject<ReturnMsgModel>(serverInfoStr);
        if (returnMsg.status)
        {
            Console.WriteLine("===服务区列表如下：==========================");
            List<ServerModel> allServerList = returnMsg.data;
            if (allServerList.Count > 0)
            {
                int ServerIndex = 0;
                foreach (var item in allServerList)
                {
                    string status = item.Status == 1 ? "开放中" : "关闭中";
                    Console.WriteLine($"{ServerIndex + 1}:{item.ServerName}[{item.IP}]-状态：{status}");
                    ServerIndex++;
                }
            }
            Console.Write("===请输入要登录的服务区编号：");
            var selectServer = Console.ReadLine();
            return allServerList[Convert.ToInt32(selectServer) - 1];
        }
        else
        {
            Console.WriteLine("未获取到服务器列表,请联系管理员...");
            return null;
        }
    }
}